﻿using DoNet.ApiHttpClient.Entitys;
using DoNet.Common.Helpers;
using Microsoft.Extensions.DependencyInjection;
using System.Net;
using System.Security.Authentication;

namespace DoNet.ApiHttpClient.WechatMch
{
    /// <summary>
    /// 微信支付 HttpClient 请求服务
    /// </summary>
    public static class WechatMchSetup
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        public static void AddHttpClientWechatMch(this IServiceCollection services)
        {
            // 注册服务
            services.AddSingleton<WechatMchManager>(provider => new WechatMchManager(provider.GetRequiredService<ICertificateLoader>(), refreshInterval: TimeSpan.FromHours(1)));
            services.AddTransient<WechatMchHttpHandler>();

            string httpClientName = "WechatMchClient";
            var wechatMchClient = ConfigHelper.GetSection<HttpClientApi>("ApiHttpClients:" + httpClientName);
            if (wechatMchClient != null)
            {
                var sslProtocols = SslHelper.GetSsl(wechatMchClient.SslProtocols);
                if (wechatMchClient.Domains.Count > 0)
                {
                    //循环API域名
                    foreach (var api in wechatMchClient.Domains)
                    {
                        var httpClientBuilder = services.AddHttpClient($"{httpClientName}_{api.index}", client =>
                        {
                            client.BaseAddress = new Uri(DomainHelper.GetDomainName(api.domain, "", wechatMchClient.IsUseHttps));
                        });
                        httpClientBuilder.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
                        {
                            SslProtocols = sslProtocols
                        });
                        httpClientBuilder.AddHttpMessageHandler<WechatMchHttpHandler>();
                        httpClientBuilder.ConfigurePrimaryHttpMessageHandler(() => new CertBindingHandler()
                        {
                            AutomaticDecompression = DecompressionMethods.GZip
                        });
                    }
                }
            }

            // 注册服务
            services.AddSingleton<WechatMchService>(); 
        }
    }
}
